<?php

namespace App\Http\Controllers\Admin;

use App\Events\UpdateMenuSession;
use App\Models\AdminPermission;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdminPermissionController extends Controller
{

    /**
     *
     *  权限列表
     */
    public function index()
    {

        return view('admin.admin_permission.index');
    }

    public function indexPost(Request $request)
    {
        $input = $request->all();
        $dd = (new AdminPermission())->dataTable(['*'], $input ,[
            'condition' => [
                [
                    'where',
                    ['where', 'name like %?%'],
                    ['orWhere', 'rule like %?%'],
                    ['orWhere', 'pid = ?'],
                ]
            ]
        ]);
        return response()->json($dd);
    }

    /**
     *  权限添加
     */
    public function addPermission()
    {
        $all_permission = (new AdminPermission())->arrayAllPermission();

        return view('admin.admin_permission.addPermission',['all_permission' => $all_permission]);
    }

    public function addPermissionPost(Request $request)
    {
        //dd($request->all());
        $input = [
            'name' => $request->input('name'),
            'rule' => $request->input('rule'),
            'description' => $request->input('description'),
            'pid' => $request->input('pid'),
            'is_menu' => $request->input('is_menu'),
            'icon' => $request->input('icon'),
            'sort' => $request->input('sort',1)
        ];
        if($request->has('id')){
            $res = (new AdminPermission())->loadSave($input, $request->input('id'));
        }else{
            $info_rule = AdminPermission::where('rule',$input['rule'])->first();
            if(!empty($info_rule)){
                return response()->json(['code'=>0, 'msg'=>'已存在']);
            }
            $res = (new AdminPermission())->loadSave($input);
        }
        return response()->json($res);
    }

    /**
     *  权限编辑
     */
    public function editPermission($id)
    {
        $permission_info = AdminPermission::find($id);
        $all_permission = (new AdminPermission())->arrayAllPermission();

        return view('admin.admin_permission.addPermission',['id' => $id,'permission' => $permission_info, 'all_permission' => $all_permission]);
    }

    /**
     *  权限删除
     */
    public function delPermissionPost(Request $request)
    {
        $id = $request->input('id');
        $re = AdminPermission::find($id)->delete();
        if($re){
            //更新权限缓存
            event(new UpdateMenuSession());

            return response()->json(['code'=>1 ,'mgs'=>'成功']);
        }else{
            return response()->json(['code'=>0 ,'mgs'=>'失败']);
        }
    }

}
